<template>
  <a-form
    ref="formRef"
    name="platform-config"
    v-bind="formItemLayout"
    :rules="rules"
  >
    <a-form-item label="无人机巡视数据" name="relativePath">
      <div class="web-uploader-uva mb-2">
        <div v-if="showProgress" class="progress-upload">
          <div class="progress-content flex justify-between">
            <div class="flex justify-between">
              <div class="ellipsis-label">{{ currentFile?.name }}</div>
            </div>
            <div
              :class="
                fileStatus === '1'
                  ? 'fail'
                  : fileStatus === '2'
                  ? 'success'
                  : 'uploading'
              "
            >
              {{ failStatusName }}
            </div>
          </div>
          <a-progress :percent="percentNum" :show-info="false" />
        </div>
        <div v-show="!showProgress">
          <a-spin :spinning="loading">
            <div :id="props.domId" class="add-file-uva ant-btn">
              <img src="@/assets/images/upload-icon.png" />
              上传压缩文件
            </div>
          </a-spin>
          <div>{{ currentFile?.name }}</div>
        </div>
      </div>
    </a-form-item>
  </a-form>
  <div class="footer-operation-uploader-uva">
    <a-button
      v-show="showProgress"
      key="back"
      type="cancel"
      class="common-buttom"
      @click="cancelUpload"
    >
      取消
    </a-button>
    <a-button
      v-show="!showProgress"
      key="submit"
      type="submit"
      :disabled="loading || !currentFile?.name"
      @click="startUpload"
      class="common-buttom"
    >
      确认
    </a-button>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, computed } from 'vue'
import type { Rule } from 'ant-design-vue/es/form'
import { message } from 'ant-design-vue'

import { upFile } from './upload.api'
import { initWebUploader } from './ts/index'
import { isFileSizeGreaterThan1GB } from './ts/verify'
// import JSZip from 'jszip'
// import iconv from 'iconv-lite'
import { Archive } from 'libarchive.js'

Archive.init({
  workerUrl: '/js/libarchive/worker-bundle.js'
})

const props = defineProps({
  domId: {
    type: String,
    default: 'addFile'
  },
  taskId: {
    type: [String, Number],
    default: ''
  },
  dataType: {
    type: [String, Number],
    default: ''
  }
})
const emit = defineEmits([
  'cancelUpload',
  'finishedUpload',
  'startReal',
  'isUploading'
])

const fileStatusMap = ref<any>({
  '0': '正在上传',
  '1': '失败',
  '2': '成功'
})

const formRef = ref()
const rules: Record<string, Rule[]> = {}
const formItemLayout = {
  labelCol: { span: 7 },
  wrapperCol: { span: 24 }
}

const loading = ref<boolean>(false)
const showProgress = ref(false)
const percentNum = ref(0)
const fileStatus = ref<string>('0')

let uploaderInstance: any
const currentFile = ref()
onMounted(() => {
  uploaderInstance = initWebUploader(
    props.domId,
    preocessCallBack,
    finishedUpload,
    checkFileError,
    startReal,
    changeFile
  )
})
const failStatusName = computed(() => {
  return fileStatusMap.value[fileStatus.value]
})
// const maxFilePath: string = ''

// 重置
const resetFile = () => {
  loading.value = false
  uploaderInstance?.reset()
  currentFile.value = null
}

// 获取zip压缩包中所有文件夹名称
// const getFolderNamesFromZip = (file: any) => {
//   return new Promise((resolve, reject) => {
//     try {
//       const zip = new JSZip()
//       const directoryArray: any = [] // 最终的文件夹列表
//       zip
//         .loadAsync(file, {
//           decodeFileName: function (bytes: any) {
//             // 使用iconv-lite解码
//             return iconv.decode(bytes, 'gbk')
//           }
//         })
//         .then((zipData) => {
//           const folderNameMap = new Map() // 文件夹 Map 数据
//           // 压缩包数据处理
//           zipData.forEach((relativePath, zipEntry) => {
//             const zipEntryName = zipEntry.name
//             if (zipEntry.dir) {
//               directoryArray.push(zipEntryName)
//               folderNameMap.set(zipEntryName, {
//                 isEmpty: true
//               })
//             } else {
//               const folderKeys = Array.from(folderNameMap.keys()).filter((v) =>
//                 zipEntryName.includes(v)
//               )
//               for (const key of folderKeys) {
//                 const folderInfo = folderNameMap.get(key)
//                 folderNameMap.set(key, {
//                   ...folderInfo,
//                   isEmpty: false
//                 })
//               }
//             }
//           })
//           const hasEmptyFolder = Array.from(folderNameMap.values()).some(
//             (folder) => folder.isEmpty
//           )
//           if (hasEmptyFolder) {
//             throw new Error('有文件夹内容为空')
//           }
//           resolve({
//             directoryArray
//           })
//         })
//         .catch((error) => {
//           reject(error)
//         })
//     } catch (error) {
//       reject(error)
//     }
//   })
// }

// 获取rar\7z压缩包中所有文件夹名称
// const getFolderNamesFromRar = async (source: any) => {
//   const archive = await Archive.open(source)
//   const extractFiles = await archive.extractFiles() // 提取文件
//   const filesArray = await archive.getFilesArray() // 图片文件列表
//   const extractArray = extractFilePaths(extractFiles) // 处理文件夹路径
//   if (extractArray.length === filesArray.length) {
//     return {
//       directoryArray: [...new Set(filesArray.map((_: any) => _.path))]
//     }
//   } else {
//     throw new Error('有文件夹内容为空')
//   }
// }
// 改变文件
const changeFile = async (file: any) => {
  try {
    // let directoryArray: string[] = []
    // const { ext, source } = file.getSource()
    const { source } = file.getSource()
    if (isFileSizeGreaterThan1GB(source)) {
      currentFile.value = file
    } else {
      loading.value = true
      // if (ext.toLowerCase() === 'zip') {
      //   const data: any = await getFolderNamesFromZip(source)
      //   directoryArray = data.directoryArray
      // } else {
      //   const data: any = await getFolderNamesFromRar(source)
      //   directoryArray = data.directoryArray
      // }
      // const verifyData: any = await verifyPackage(directoryArray)
      // maxFilePath = verifyData.maxFilePath
      // checkData(verifyData.lineFolder)
      //   .then(() => {
      currentFile.value = file
      loading.value = false
      // })
      // .catch((err) => {
      //   console.error(err)
      //   resetFile()
      // })
    }
  } catch (error: any) {
    resetFile()
    message.error(error?.message)
    console.error(error)
  }
}

// 开始上传
const startUpload = () => {
  uploaderInstance?.upload()
  emit('isUploading', true)
}
// 停止上传
const stopUpload = () => {
  uploaderInstance?.stop(true)
}
// 取消上传
const cancelUpload = () => {
  stopUpload()
  showProgress.value = false
  percentNum.value = 0
  emit('isUploading', false)
}

const preocessCallBack = (per: number) => {
  if (per === 1) {
    per = 0.99
  }
  showProgress.value = true
  percentNum.value = Number((per * 100).toFixed(0))
}
let checkType: number = 2
const finishedUpload = (file: any, checkFileType = 2) => {
  if (checkFileType === 1) {
    checkType = checkFileType
    fileUploaded()
    addFileFun(file, checkFileType)
    return
  } else if (checkType !== 1) {
    addFileFun(file, checkFileType)
  }
  checkType = 2
}
/**
 * packStatus解压状态 1-未解压 2-解压失败 3-解压成功 4:解压成功，但是上传的图片文件不对
 */
const addFileFun = (file: any, checkFileType = 2) => {
  upFile({
    targetId: file.md5,
    fileName: file.name
  })
    .then(() => {
      loading.value = false
      showProgress.value = false
      percentNum.value = 0
      emit('finishedUpload')
      message.success('上传成功')
      emit('isUploading', false)
    })
    .catch(() => {
      loading.value = false
      showProgress.value = false
      percentNum.value = 0
      emit('cancelUpload')
      emit('isUploading', false)
    })
}
const fileUploaded = () => {
  message.success('文件已上传')
}
const checkFileError = (type: any) => {
  if (type === 'Q_TYPE_DENIED') {
    message.error('仅支持zip、7z格式文件')
  } else if (type === 'F_EXCEED_SIZE') {
    message.error('最大不可超过15G')
  }
}

const startReal = (file: any) => {
  emit('startReal')
}
onBeforeUnmount(() => {
  stopUpload()
})

defineExpose({ startUpload })
</script>
<style lang="less">
.web-uploader-uva {
  padding: 0;
  margin-left: 0.85rem;
  width: fit-content;

  .progress-upload {
    position: relative;
    top: calc(50% - 1rem);
    padding-right: 0.5rem;
    // color: @regular-text-color;

    .progress-content {
      .ellipsis-label {
        width: 7rem;
      }

      img {
        margin-right: 0.25rem;
      }

      .fail {
        color: #f00;
      }

      .success {
        color: #52c41a;
      }

      .uploading {
        color: #1677ff;
      }
    }

    .ant-progress-inner {
      height: 0.1875rem;
      background: rgb(217 225 250 / 10%);
    }
  }

  .add-file-uva {
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 8rem;
    height: 1.9375rem;
    min-height: 1.9375rem;
    background-color: transparent;

    .webuploader-element-invisible {
      width: 100%;
      font-size: 0;
      cursor: pointer;
    }

    img {
      margin-right: 0.5rem;
      width: 0.8rem;
    }

    div {
      position: absolute;
      inset: auto !important;
      opacity: 0;
    }

    .webuploader-pick {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 100%;
      height: 100%;
      opacity: 1;

      img {
        margin-right: 0.5rem;
      }
    }
  }
}

.footer-operation-uploader-uva {
  position: absolute;
  right: 1.25rem;
  bottom: 1rem;
}
</style>
